package com.zsck.pos.adapter;

import android.content.Context;
import android.widget.BaseAdapter;


import java.util.ArrayList;
import java.util.List;

public abstract class ContentAdapter<T> extends BaseAdapter {

    protected Context context;
    protected SelectedCallBack mCallBack;
    protected List<T> mSelectedIndex = new ArrayList<>();

    protected List<T> mItems = new ArrayList<>();


    public ContentAdapter(Context context, List<T> items) {
        this.mItems = items;
        this.context = context;
        if(context instanceof SelectedCallBack){
            mCallBack = (SelectedCallBack) context;
            mCallBack.onSelectedChange(mSelectedIndex,false);
        }
    }

    @Override
    public int getCount() {
        return mItems.size();
    }


    public List<T> getSelectedIndex(){
        return mSelectedIndex;
    }

    /**
     * 全选状态切换,全部选中时取消全选,没有全部选中时全部选中
     */
    public boolean  allSelectedSwitch(){
        boolean isAllSelected = isAllSelected();
        mSelectedIndex.clear();
        if(!isAllSelected){
            mSelectedIndex.addAll(mItems);
        }
        notifyDataSetChanged();
        if(mCallBack != null){
            mCallBack.onSelectedChange(mSelectedIndex,!isAllSelected);
        }
        return !isAllSelected;
    }

    public boolean isAllSelected(){
        boolean isAllSelected = true;
        for(int i = 0 ; i < mItems.size(); i++){
            if(mSelectedIndex.size() == 0 || !mSelectedIndex.contains(mItems.get(i))){
                isAllSelected = false;
                break;
            }
        }
        return isAllSelected;
    }


    public void setData(List<T> items){
        this.mItems = items;
        notifyDataSetChanged();
    }

    public void addData(List<T> items){
        this.mItems.addAll(items);
        notifyDataSetChanged();
    }
}

